<?php
/**
 *+------------------
 * Lflow
 *+------------------
 * Copyright (c) 2023~2030 gitee.com/liu_guan_qing All rights reserved.本版权不可删除，侵权必究
 *+------------------
 * Author: Mr.April(405784684@qq.com)
 *+------------------
 */
declare (strict_types=1);

namespace lflow\handlers\impl;

use lflow\ckpt\SubProcessCkpt;
use lflow\core\Execution;
use lflow\handlers\IHandler;
use lflow\lib\util\AssertHelper;
use lflow\lib\util\ConfigHelper;

/**
 * 启动子流程处理器
 *
 * @author Mr.April
 * @since  1.0
 */
class StartSubProcessHandler implements IHandler
{
    /**
     * @var \lflow\ckpt\SubProcessCkpt
     */
    private SubProcessCkpt $ckpt;

    /**
     * 是否以future方式执行启动子流程任务
     */
    private bool $isFutureRunning = false;

    public function __construct(SubProcessCkpt $ckpt)
    {
        $this->ckpt      = $ckpt;
        $isFutureRunning = ConfigHelper::getProperty('is_future_running');
        if (!empty($isFutureRunning)) {
            $this->isFutureRunning = true;
        }
    }

    /**
     * 子流程输出处理
     * @param \lflow\core\Execution $execution
     */
    public function handle(Execution $execution): void
    {
         //根据子流程模型名称获取子流程定义对象
        $engine  = $execution->getEngine();
        $process = $engine->process()->getProcessByVersion($this->ckpt->getProcessName(), $this->ckpt->getVersion());

        $child = $execution->createSubExecution($execution, $process, $this->ckpt->getName());
        $order = null;
        if ($this->isFutureRunning) {
//            // 创建单个线程执行器来执行启动子流程的任务
//            $es = \Executors::newSingleThreadExecutor();
//            // 提交执行任务，并返回Future
//            $future = $es->submit(new \ExecuteTask($execution, $process, $this->ckpt->getName()));
//
//            try {
//                $es->shutdown();
//                $order = $future->get();
//            } catch (\InterruptedException $e) {
//                throw new \SnakerException("创建子流程线程被强制终止执行", $e->getCause());
//            } catch (\ExecutionException $e) {
//                throw new \SnakerException("创建子流程线程执行异常.", $e->getCause());
//            }
        } else {
            $order = $engine->startInstanceByExecution($child);
        }
        AssertHelper::notNull($order, "子流程创建失败");
        $tasksE = $engine->query()->getActiveTasks(['order_id' => $order->getData('id')]);
        $tasks  = [];
        foreach ($tasksE['list'] as $task) {
            $tasks[] = $task;
        }
        $execution->addTasks($tasks);
    }
}
